/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainDetailPanel.java
 *
 * Created on 29/12/2010, 14:19:12
 */
package net.stuffrepos.bricknetcenter.gui.informations;

import java.util.LinkedList;
import net.stuffrepos.bricknetcenter.database.DataEvent;
import net.stuffrepos.bricknetcenter.database.DataListener;
import net.stuffrepos.bricknetcenter.database.DataManager;
import net.stuffrepos.bricknetcenter.database.schema.HttpRequest;
import net.stuffrepos.bricknetcenter.database.schema.Information;
import net.stuffrepos.bricknetcenter.gui.FormatHelper;
import net.stuffrepos.bricknetcenter.provider.HttpProviderManager;
import net.stuffrepos.util.listeners.Listener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Eduardo H. Bogoni <eduardobogoni@gmail.com>
 */
public class MainDetailPanel extends javax.swing.JPanel {

    private static final int REQUESTS_LIMIT = 20;
    private LinkedList<HttpRequest> requests = new LinkedList<HttpRequest>();
    private static final Log log = LogFactory.getLog(MainDetailPanel.class);

    /** Creates new form MainDetailPanel */
    public MainDetailPanel() {
        initComponents();
        FormatHelper.formatTitleLabel(title);

        refreshCountersInformation();
        refreshLastRequestsInformation();

        DataManager.getInstance().addDataListener(new DataListener() {

            @Override
            public void dataChanged(DataEvent event) {
                refreshCountersInformation();
            }
        });

        HttpProviderManager.getInstance().addRequestListener(new Listener<HttpRequest>() {

            @Override
            public void onChange(HttpRequest source) {                
                if (requests.contains(source)) {
                    requests.remove(source);
                } else if (requests.size() >= REQUESTS_LIMIT) {
                    requests.poll();
                }

                requests.add(source);

                refreshLastRequestsInformation();
            }
        });
    }

    public void refreshCountersInformation() {
        try {
            inventoriesCount.setText(
                    buildCountersInformation());

        } catch (Exception ex) {
            log.warn("", ex);
        }
    }

    public void refreshLastRequestsInformation() {
        lastRequestsInformation.setText(buildLastRequestsInformation());
    }

    private String buildCountersInformation() throws Exception {
        StringBuilder b = new StringBuilder();

        b.append("<html>");

        b.append("Total: ").append(DataManager.getInstance().getInformationManager().getAllInformationsCount()).append("<br/>");

        for (Information.Type type : Information.Type.values()) {
            b.append(type.toString()).
                    append(": ").
                    append(DataManager.getInstance().
                    getInformationManager().getInformationsCount(type)).append("<br/>");
        }

        b.append("</html>");

        return b.toString();
    }

    private String buildLastRequestsInformation() {
        StringBuilder b = new StringBuilder();
        b.append("<html>");

        b.append("<table style='border: thin solid black; border-collapse: collapse'>");
        b.append("<tr>");
        b.append("<th>URL</th>");
        b.append("<th>Parser</th>");
        b.append("<th>Priority</th>");
        b.append("<th>Status</th>");
        b.append("</tr>");

        if (requests.isEmpty()) {
            b.append("<tr>");
            b.append("<td colspan='4'><i>No last requests.</i></td>");
            b.append("</tr>");
        } else {



            for (HttpRequest request : requests) {
                b.append("<tr>");
                b.append("<th>").append(request.getUrlSpecification()).append("</th>");
                b.append("<th>").append(getParserName(request.getParserClass())).append("</th>");
                b.append("<th>").append(request.getPriority()).append("</th>");
                b.append("<th>").append(request.getStatus()).append("</th>");
                b.append("</tr>");
            }
        }

        b.append("</table>");

        b.append("</html>");


        return b.toString();
    }
    
    private String getParserName(String parserClassName) {                
        try {
            return Class.forName(parserClassName).getSimpleName();
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        }
    }        

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        title = new javax.swing.JLabel();
        informationsSplitPane = new javax.swing.JSplitPane();
        inventoriesCount = new javax.swing.JLabel();
        lastRequestsInformationScrollPane = new javax.swing.JScrollPane();
        lastRequestsInformation = new javax.swing.JLabel();

        title.setText("Informations");

        inventoriesCount.setText("Inventory's Counters ");
        inventoriesCount.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        informationsSplitPane.setLeftComponent(inventoriesCount);

        lastRequestsInformation.setText("Last Requests Information");
        lastRequestsInformation.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        lastRequestsInformationScrollPane.setViewportView(lastRequestsInformation);

        informationsSplitPane.setRightComponent(lastRequestsInformationScrollPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(title)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(informationsSplitPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(title)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(informationsSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSplitPane informationsSplitPane;
    private javax.swing.JLabel inventoriesCount;
    private javax.swing.JLabel lastRequestsInformation;
    private javax.swing.JScrollPane lastRequestsInformationScrollPane;
    private javax.swing.JLabel title;
    // End of variables declaration//GEN-END:variables
}
